<template>
  <div class="merchant-order">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待付款" value="pending_payment" />
            <el-option label="待确认" value="pending_confirm" />
            <el-option label="待服务" value="pending_service" />
            <el-option label="服务中" value="in_service" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="已退款" value="refunded" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="客户信息">
          <el-input v-model="searchForm.customerInfo" placeholder="手机号/姓名" clearable />
        </el-form-item>
        <el-form-item label="评价状态">
          <el-select v-model="searchForm.reviewStatus" placeholder="请选择状态" clearable>
            <el-option label="已评价" value="reviewed" />
            <el-option label="未评价" value="unreviewed" />
            <el-option label="已回复" value="replied" />
            <el-option label="未回复" value="unreplied" />
          </el-select>
        </el-form-item>
        <el-form-item label="异常状态">
          <el-select v-model="searchForm.exceptionStatus" placeholder="请选择状态" clearable>
            <el-option label="无异常" value="normal" />
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已处理" value="resolved" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleExport">导出订单</el-button>
          <el-button type="warning" @click="handleReviewManage">评价管理</el-button>
          <el-button type="danger" @click="handleExceptionManage">异常处理</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleExport" v-permission="'merchant:order:export'">
        <el-icon><Download /></el-icon>导出订单
      </el-button>
      <el-button type="success" @click="handleBatchConfirm" :disabled="!selectedOrders.length" v-permission="'merchant:order:confirm'">
        <el-icon><Check /></el-icon>批量确认
      </el-button>
      <el-button type="warning" @click="handleBatchCancel" :disabled="!selectedOrders.length" v-permission="'merchant:order:cancel'">
        <el-icon><Close /></el-icon>批量取消
      </el-button>
      <el-button type="info" @click="handleReviewManage" v-permission="'merchant:order:review'">
        <el-icon><ChatDotRound /></el-icon>评价管理
      </el-button>
      <el-button type="danger" @click="handleExceptionManage" v-permission="'merchant:order:exception'">
        <el-icon><Warning /></el-icon>异常处理
      </el-button>
    </div>

    <!-- 订单列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="orderList"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单编号" min-width="180" show-overflow-tooltip />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="customerPhone" label="联系电话" width="120" />
        <el-table-column prop="serviceName" label="服务项目" min-width="150" show-overflow-tooltip />
        <el-table-column prop="amount" label="订单金额" width="120">
          <template #default="{ row }">
            ¥{{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getOrderStatusTag(row.status)">
              {{ getOrderStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="100">
          <template #default="{ row }">
            {{ getPaymentMethodLabel(row.paymentMethod) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" min-width="180" />
        <el-table-column prop="appointmentTime" label="预约时间" min-width="180" />
        <el-table-column prop="reviewStatus" label="评价状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getReviewStatusTag(row.reviewStatus)">
              {{ getReviewStatusLabel(row.reviewStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="exceptionStatus" label="异常状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getExceptionStatusTag(row.exceptionStatus)">
              {{ getExceptionStatusLabel(row.exceptionStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleDetail(row)" v-permission="'merchant:order:detail'">
              详情
            </el-button>
            <el-button 
              v-if="row.status === 'pending_confirm'"
              type="success" 
              link 
              @click="handleConfirm(row)"
              v-permission="'merchant:order:confirm'"
            >
              确认
            </el-button>
            <el-button 
              v-if="row.status === 'pending_service'"
              type="primary" 
              link 
              @click="handleStartService(row)"
              v-permission="'merchant:order:service'"
            >
              开始服务
            </el-button>
            <el-button 
              v-if="row.status === 'in_service'"
              type="success" 
              link 
              @click="handleComplete(row)"
              v-permission="'merchant:order:complete'"
            >
              完成服务
            </el-button>
            <el-button 
              v-if="['pending_payment', 'pending_confirm'].includes(row.status)"
              type="danger" 
              link 
              @click="handleCancel(row)"
              v-permission="'merchant:order:cancel'"
            >
              取消
            </el-button>
            <el-button 
              v-if="row.status === 'completed'"
              type="primary" 
              link 
              @click="handleRefund(row)"
              v-permission="'merchant:order:refund'"
            >
              退款
            </el-button>
            <el-button
              v-if="row.reviewStatus === 'reviewed' && !row.replyContent"
              type="primary"
              link
              @click="handleReplyReview(row)"
              v-permission="'merchant:order:review:reply'"
            >
              回复评价
            </el-button>
            <el-button
              v-if="row.reviewStatus === 'reviewed' && row.replyContent"
              type="primary"
              link
              @click="handleEditReplyReview(row)"
              v-permission="'merchant:order:review:reply'"
            >
              修改回复
            </el-button>
            <el-button
              v-if="row.exceptionStatus !== 'normal'"
              type="danger"
              link
              @click="handleViewException(row)"
              v-permission="'merchant:order:exception:view'"
            >
              查看异常
            </el-button>
            <el-button
              v-if="row.exceptionStatus === 'pending'"
              type="danger"
              link
              @click="handleProcessException(row)"
              v-permission="'merchant:order:exception:process'"
            >
              处理异常
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getOrderStatusTag(currentOrder.status)">
            {{ getOrderStatusLabel(currentOrder.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="客户姓名">{{ currentOrder.customerName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentOrder.customerPhone }}</el-descriptions-item>
        <el-descriptions-item label="服务项目">{{ currentOrder.serviceName }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">¥{{ currentOrder.amount?.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ getPaymentMethodLabel(currentOrder.paymentMethod) }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ currentOrder.createTime }}</el-descriptions-item>
        <el-descriptions-item label="预约时间">{{ currentOrder.appointmentTime }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentOrder.remark || '无' }}</el-descriptions-item>
      </el-descriptions>

      <!-- 订单状态记录 -->
      <div class="order-timeline">
        <h3>订单状态记录</h3>
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in currentOrder.statusLogs"
            :key="index"
            :type="getTimelineItemType(activity.status)"
            :timestamp="activity.time"
          >
            {{ getOrderStatusLabel(activity.status) }}
            <div class="timeline-content" v-if="activity.remark">
              {{ activity.remark }}
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>

      <!-- 操作记录 -->
      <div class="order-logs">
        <h3>操作记录</h3>
        <el-table :data="currentOrder.operationLogs" border>
          <el-table-column prop="operator" label="操作人" width="120" />
          <el-table-column prop="action" label="操作" width="120" />
          <el-table-column prop="time" label="操作时间" min-width="180" />
          <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
        </el-table>
      </div>
    </el-dialog>

    <!-- 退款对话框 -->
    <el-dialog
      v-model="refundDialogVisible"
      title="订单退款"
      width="500px"
    >
      <el-form
        ref="refundFormRef"
        :model="refundForm"
        :rules="refundRules"
        label-width="100px"
      >
        <el-form-item label="退款金额" prop="amount">
          <el-input-number 
            v-model="refundForm.amount" 
            :min="0" 
            :max="currentOrder.amount"
            :precision="2"
            :step="0.01"
          />
        </el-form-item>
        <el-form-item label="退款原因" prop="reason">
          <el-input
            v-model="refundForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入退款原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="refundDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRefundSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 回复评价对话框 -->
    <el-dialog
      v-model="reviewDialog.visible"
      :title="reviewDialog.isEdit ? '修改回复' : '回复评价'"
      width="500px"
    >
      <el-form
        ref="reviewFormRef"
        :model="reviewDialog.form"
        :rules="reviewDialog.rules"
        label-width="80px"
      >
        <el-form-item label="评价内容">
          <div class="review-content">
            <div class="review-score">
              <el-rate v-model="reviewDialog.review.score" disabled />
              <span class="score-text">{{ reviewDialog.review.score }}分</span>
            </div>
            <div class="review-text">{{ reviewDialog.review.content }}</div>
            <div v-if="reviewDialog.review.images?.length" class="review-images">
              <el-image
                v-for="(img, index) in reviewDialog.review.images"
                :key="index"
                :src="img"
                :preview-src-list="reviewDialog.review.images"
                fit="cover"
                class="review-image"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="回复内容" prop="content">
          <el-input
            v-model="reviewDialog.form.content"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitReviewReply">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 异常详情对话框 -->
    <el-dialog
      v-model="exceptionDialog.visible"
      title="异常详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ exceptionDialog.data.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="异常类型">
          <el-tag :type="getExceptionTypeTag(exceptionDialog.data.type)">
            {{ getExceptionTypeLabel(exceptionDialog.data.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="异常描述" :span="2">
          {{ exceptionDialog.data.description }}
        </el-descriptions-item>
        <el-descriptions-item label="处理状态">
          <el-tag :type="getExceptionStatusTag(exceptionDialog.data.status)">
            {{ getExceptionStatusLabel(exceptionDialog.data.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="异常时间">{{ exceptionDialog.data.createTime }}</el-descriptions-item>
        <el-descriptions-item label="处理人">{{ exceptionDialog.data.handler || '-' }}</el-descriptions-item>
        <el-descriptions-item label="处理时间">{{ exceptionDialog.data.handleTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="处理方案" :span="2">{{ exceptionDialog.data.solution || '-' }}</el-descriptions-item>
      </el-descriptions>

      <div v-if="exceptionDialog.data.logs?.length" class="exception-logs">
        <div class="logs-title">处理记录</div>
        <el-timeline>
          <el-timeline-item
            v-for="(log, index) in exceptionDialog.data.logs"
            :key="index"
            :type="getLogTypeTag(log.type)"
            :timestamp="log.createTime"
          >
            {{ log.content }}
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>

    <!-- 处理异常对话框 -->
    <el-dialog
      v-model="processExceptionDialog.visible"
      title="处理异常"
      width="500px"
    >
      <el-form
        ref="processExceptionFormRef"
        :model="processExceptionDialog.form"
        :rules="processExceptionDialog.rules"
        label-width="80px"
      >
        <el-form-item label="处理方案" prop="solution">
          <el-input
            v-model="processExceptionDialog.form.solution"
            type="textarea"
            :rows="4"
            placeholder="请输入处理方案"
          />
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="processExceptionDialog.form.status" placeholder="请选择状态">
            <el-option label="处理中" value="processing" />
            <el-option label="已处理" value="resolved" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processExceptionDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitProcessException">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, Check, Close, ChatDotRound, Warning } from '@element-plus/icons-vue'
import {
  getMerchantOrderList,
  getMerchantOrderDetail,
  updateMerchantOrderStatus,
  exportMerchantOrders,
  refundMerchantOrder,
  replyMerchantOrderReview,
  getMerchantOrderExceptionDetail,
  processMerchantOrderException
} from '@/api/merchant'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  status: '',
  dateRange: [],
  customerInfo: '',
  reviewStatus: '',
  exceptionStatus: ''
})

// 分页信息
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 订单列表数据
const loading = ref(false)
const orderList = ref([])
const selectedOrders = ref([])

// 订单详情对话框
const detailDialogVisible = ref(false)
const currentOrder = ref({})

// 退款对话框
const refundDialogVisible = ref(false)
const refundFormRef = ref(null)
const refundForm = reactive({
  amount: 0,
  reason: ''
})

// 退款表单验证规则
const refundRules = {
  amount: [
    { required: true, message: '请输入退款金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '退款金额必须大于0', trigger: 'blur' }
  ],
  reason: [
    { required: true, message: '请输入退款原因', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

// 评价对话框
const reviewDialog = reactive({
  visible: false,
  isEdit: false,
  review: {},
  form: {
    content: ''
  },
  rules: {
    content: [
      { required: true, message: '请输入回复内容', trigger: 'blur' },
      { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
    ]
  }
})

const reviewFormRef = ref(null)

// 异常对话框
const exceptionDialog = reactive({
  visible: false,
  data: {}
})

// 处理异常对话框
const processExceptionDialog = reactive({
  visible: false,
  id: '',
  form: {
    solution: '',
    status: 'processing'
  },
  rules: {
    solution: [
      { required: true, message: '请输入处理方案', trigger: 'blur' },
      { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
    ],
    status: [
      { required: true, message: '请选择处理状态', trigger: 'change' }
    ]
  }
})

const processExceptionFormRef = ref(null)

// 获取订单状态标签类型
const getOrderStatusTag = (status) => {
  const statusMap = {
    pending_payment: 'warning',
    pending_confirm: 'info',
    pending_service: 'primary',
    in_service: 'success',
    completed: 'success',
    cancelled: 'danger',
    refunded: 'info'
  }
  return statusMap[status] || ''
}

// 获取订单状态标签文本
const getOrderStatusLabel = (status) => {
  const statusMap = {
    pending_payment: '待付款',
    pending_confirm: '待确认',
    pending_service: '待服务',
    in_service: '服务中',
    completed: '已完成',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return statusMap[status] || status
}

// 获取支付方式标签文本
const getPaymentMethodLabel = (method) => {
  const methodMap = {
    wechat: '微信支付',
    alipay: '支付宝',
    balance: '余额支付',
    cash: '现金支付'
  }
  return methodMap[method] || method
}

// 获取时间线项目类型
const getTimelineItemType = (status) => {
  const typeMap = {
    pending_payment: 'warning',
    pending_confirm: 'info',
    pending_service: 'primary',
    in_service: 'success',
    completed: 'success',
    cancelled: 'danger',
    refunded: 'info'
  }
  return typeMap[status] || ''
}

// 获取评价状态标签类型
const getReviewStatusTag = (status) => {
  const statusMap = {
    unreviewed: 'info',
    reviewed: 'success',
    replied: 'success',
    unreplied: 'warning'
  }
  return statusMap[status] || 'info'
}

// 获取评价状态标签文本
const getReviewStatusLabel = (status) => {
  const statusMap = {
    unreviewed: '未评价',
    reviewed: '已评价',
    replied: '已回复',
    unreplied: '待回复'
  }
  return statusMap[status] || status
}

// 获取异常状态标签类型
const getExceptionStatusTag = (status) => {
  const statusMap = {
    normal: 'success',
    pending: 'warning',
    processing: 'primary',
    resolved: 'success'
  }
  return statusMap[status] || 'info'
}

// 获取异常状态标签文本
const getExceptionStatusLabel = (status) => {
  const statusMap = {
    normal: '无异常',
    pending: '待处理',
    processing: '处理中',
    resolved: '已处理'
  }
  return statusMap[status] || status
}

// 获取异常类型标签类型
const getExceptionTypeTag = (type) => {
  const typeMap = {
    payment: 'danger',
    shipping: 'warning',
    refund: 'info',
    service: 'primary',
    other: 'info'
  }
  return typeMap[type] || 'info'
}

// 获取异常类型标签文本
const getExceptionTypeLabel = (type) => {
  const typeMap = {
    payment: '支付异常',
    shipping: '发货异常',
    refund: '退款异常',
    service: '服务异常',
    other: '其他异常'
  }
  return typeMap[type] || type
}

// 获取日志类型标签类型
const getLogTypeTag = (type) => {
  const typeMap = {
    create: 'primary',
    process: 'success',
    close: 'info'
  }
  return typeMap[type] || 'info'
}

// 获取订单列表
const getOrderListData = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1],
      page: page.current,
      size: page.size
    }
    const { data } = await getMerchantOrderList(params)
    orderList.value = data.list
    page.total = data.total
  } catch (error) {
    console.error('获取订单列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.current = 1
  getOrderListData()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedOrders.value = selection
}

// 查看订单详情
const handleDetail = async (row) => {
  try {
    const { data } = await getMerchantOrderDetail(row.id)
    currentOrder.value = data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取订单详情失败:', error)
  }
}

// 确认订单
const handleConfirm = async (row) => {
  try {
    await ElMessageBox.confirm('确认接受该订单吗？', '提示', {
      type: 'warning'
    })
    await updateMerchantOrderStatus(row.id, { status: 'pending_service' })
    ElMessage.success('订单已确认')
    getOrderListData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认订单失败:', error)
    }
  }
}

// 批量确认订单
const handleBatchConfirm = async () => {
  if (!selectedOrders.value.length) return
  
  const pendingOrders = selectedOrders.value.filter(order => order.status === 'pending_confirm')
  if (!pendingOrders.length) {
    ElMessage.warning('选中的订单中没有待确认的订单')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确认接受选中的 ${pendingOrders.length} 个订单吗？`, '提示', {
      type: 'warning'
    })
    await Promise.all(
      pendingOrders.map(order => 
        updateMerchantOrderStatus(order.id, { status: 'pending_service' })
      )
    )
    ElMessage.success('批量确认成功')
    getOrderListData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量确认订单失败:', error)
    }
  }
}

// 开始服务
const handleStartService = async (row) => {
  try {
    await ElMessageBox.confirm('确认开始服务吗？', '提示', {
      type: 'warning'
    })
    await updateMerchantOrderStatus(row.id, { status: 'in_service' })
    ElMessage.success('已开始服务')
    getOrderListData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('开始服务失败:', error)
    }
  }
}

// 完成服务
const handleComplete = async (row) => {
  try {
    await ElMessageBox.confirm('确认完成服务吗？', '提示', {
      type: 'warning'
    })
    await updateMerchantOrderStatus(row.id, { status: 'completed' })
    ElMessage.success('服务已完成')
    getOrderListData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成服务失败:', error)
    }
  }
}

// 取消订单
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm('确认取消该订单吗？', '提示', {
      type: 'warning'
    })
    await updateMerchantOrderStatus(row.id, { status: 'cancelled' })
    ElMessage.success('订单已取消')
    getOrderListData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
    }
  }
}

// 批量取消订单
const handleBatchCancel = async () => {
  if (!selectedOrders.value.length) return
  
  const cancelableOrders = selectedOrders.value.filter(order => 
    ['pending_payment', 'pending_confirm'].includes(order.status)
  )
  if (!cancelableOrders.length) {
    ElMessage.warning('选中的订单中没有可取消的订单')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确认取消选中的 ${cancelableOrders.length} 个订单吗？`, '提示', {
      type: 'warning'
    })
    await Promise.all(
      cancelableOrders.map(order => 
        updateMerchantOrderStatus(order.id, { status: 'cancelled' })
      )
    )
    ElMessage.success('批量取消成功')
    getOrderListData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量取消订单失败:', error)
    }
  }
}

// 退款
const handleRefund = (row) => {
  currentOrder.value = row
  refundForm.amount = row.amount
  refundForm.reason = ''
  refundDialogVisible.value = true
}

// 提交退款
const handleRefundSubmit = async () => {
  if (!refundFormRef.value) return
  
  try {
    await refundFormRef.value.validate()
    await refundMerchantOrder(currentOrder.value.id, refundForm)
    ElMessage.success('退款申请已提交')
    refundDialogVisible.value = false
    getOrderListData()
  } catch (error) {
    console.error('提交退款失败:', error)
  }
}

// 跳转到评价管理页面
const handleReviewManage = () => {
  router.push('/merchant/order/review')
}

// 回复评价
const handleReplyReview = (row) => {
  reviewDialog.isEdit = false
  reviewDialog.review = row.review
  reviewDialog.form.content = ''
  reviewDialog.visible = true
}

// 修改回复
const handleEditReplyReview = (row) => {
  reviewDialog.isEdit = true
  reviewDialog.review = row.review
  reviewDialog.form.content = row.review.replyContent
  reviewDialog.visible = true
}

// 提交评价回复
const submitReviewReply = async () => {
  if (!reviewFormRef.value) return
  
  try {
    await reviewFormRef.value.validate()
    await replyMerchantOrderReview(reviewDialog.review.id, {
      content: reviewDialog.form.content
    })
    ElMessage.success(reviewDialog.isEdit ? '修改回复成功' : '回复成功')
    reviewDialog.visible = false
    getOrderListData()
  } catch (error) {
    console.error('提交评价回复失败:', error)
  }
}

// 导出订单
const handleExport = async () => {
  try {
    const params = {
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }
    await exportMerchantOrders(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出订单失败:', error)
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  page.size = val
  getOrderListData()
}

// 页码变化
const handleCurrentChange = (val) => {
  page.current = val
  getOrderListData()
}

// 跳转到异常处理页面
const handleExceptionManage = () => {
  router.push('/merchant/order/exception')
}

// 查看异常
const handleViewException = async (row) => {
  try {
    const { data } = await getMerchantOrderExceptionDetail(row.exceptionId)
    exceptionDialog.data = data
    exceptionDialog.visible = true
  } catch (error) {
    console.error('获取异常详情失败:', error)
  }
}

// 处理异常
const handleProcessException = (row) => {
  processExceptionDialog.id = row.exceptionId
  processExceptionDialog.form = {
    solution: '',
    status: 'processing'
  }
  processExceptionDialog.visible = true
}

// 提交异常处理
const submitProcessException = async () => {
  if (!processExceptionFormRef.value) return
  
  try {
    await processExceptionFormRef.value.validate()
    await processMerchantOrderException(processExceptionDialog.id, processExceptionDialog.form)
    ElMessage.success('处理异常成功')
    processExceptionDialog.visible = false
    getOrderListData()
  } catch (error) {
    console.error('提交异常处理失败:', error)
  }
}

onMounted(() => {
  getOrderListData()
})
</script>

<style lang="scss" scoped>
.merchant-order {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .action-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .order-timeline {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #eee;

    h3 {
      margin-bottom: 20px;
      font-size: 16px;
      font-weight: 500;
    }

    .timeline-content {
      font-size: 13px;
      color: #666;
      margin-top: 5px;
    }
  }

  .order-logs {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #eee;

    h3 {
      margin-bottom: 20px;
      font-size: 16px;
      font-weight: 500;
    }
  }

  .review-content {
    .review-score {
      margin-bottom: 10px;
      
      .score-text {
        margin-left: 10px;
        color: #ff9900;
      }
    }
    
    .review-text {
      margin-bottom: 10px;
      color: #606266;
    }
    
    .review-images {
      display: flex;
      gap: 10px;
      
      .review-image {
        width: 80px;
        height: 80px;
        border-radius: 4px;
      }
    }
  }

  .exception-logs {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #EBEEF5;
    
    .logs-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 20px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 